<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\api\House;
use App\Service\Es;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;

class RentHouseController extends Controller
{
    public function rentHouseList()
    {
        $data = House::where('house_type','2')->get();
        return ['code' => 200, 'msg' => '成功', 'data' => $data];
    }

    public function rentHouseAdd()
    {
        $data = House::all()->toArray();
        $client = ClientBuilder::create()->setHosts([
            [
                'host'   => config('es.host'),
                'port'   => config('es.port'),
                'scheme' => config('es.scheme'),
                'user'   => config('es.user'),
                'pass'   => config('es.pass')
            ]
        ])->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
            ->setRetries(10)->build();
        foreach ($data as $k=>$v){
            $params = [
                'index'=>'rent_house',
                'type'=>'_doc',
                'id'=>$v['id'],
                'body'=>$v
            ];
            $r = $client->index($params);
        }
        $response = $client->index($params);
        print_r($response);
    }


    public function rentHouseSearch(Request $request)
    {
        $house_name = $request->get('text');

        if(!empty($house_name)) {
            $response = (new Es())->rentHouseEs($house_name);

            foreach ($response['hits']['hits'] as $k => $v) {

                $v['_source']['house_name'] = $v['highlight']['house_name'][0];

                $Data[] = $v['_source'];
            }
            return ['code' => 200, 'msg' => 'ok', 'data' => $Data];
        }else{
            $data = House::where('house_type','2')->get();
            return ['code'=>200,'msg'=>'ok','data'=>$data];
        }
    }
}
